package com.example;

import com.alibaba.fastjson.JSONObject;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.util.List;

public class ExampleMain {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-persistence-unit");
        persistEmployee(emf);
        findDistinctDepartment(emf);
        emf.close();
    }
    private static void persistEmployee(EntityManagerFactory emf){
        EntityManager em = emf.createEntityManager();
        Employee employee1 = new Employee("Diana","IT",3000);
        Employee employee2 = new Employee("Rose","Admin",4000);
        Employee employee3 = new Employee("Denise","IT",1500);
        em.getTransaction().begin();
        em.persist(employee1);
        em.persist(employee2);
        em.persist(employee3);
        em.getTransaction().commit();
        em.close();
    }
    private static void findByDepartment(EntityManagerFactory emf){
        EntityManager em = emf.createEntityManager();
        Query query = em.createQuery("select e from Employee e where e.department = :department");
        query.setParameter("department","IT");
        List<Employee> employees = query.getResultList();
        for (Employee employee : employees) {
            System.err.println(JSONObject.toJSONString(employee,false));
        }

    }
    private static void findEmployeeByOrderBy(EntityManagerFactory emf){
        EntityManager em = emf.createEntityManager();
        Query query = em.createQuery("select e from Employee e order by e.salary desc");
        List<Employee> employees = query.getResultList();
        for (Employee employee : employees) {
            System.err.println(JSONObject.toJSONString(employee,false));
        }
    }
    private static void findDistinctDepartment(EntityManagerFactory emf){
        EntityManager em = emf.createEntityManager();
        Query query = em.createQuery("select distinct e.department from Employee e");
        List<String> departments = query.getResultList();
        for (String department : departments) {
            System.err.println(department);
        }
    }
}
